package initialize

import (
	"cart_srv/global"
	"fmt"
	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
)

func InitConsul() {
	config := api.DefaultConfig()
	config.Address = fmt.Sprintf("%s:%d", global.AppConf.ConsulConfig.Host, global.AppConf.ConsulConfig.Port)
	client, err := api.NewClient(config)
	if err != nil {
		zap.S().Error(err)
		return
	}
	//健康检测
	check := &api.AgentServiceCheck{
		Interval:                       "5s",
		Timeout:                        "2s",
		GRPC:                           fmt.Sprintf("%s:%d", global.AppConf.Ip, global.AppConf.Port),
		DeregisterCriticalServiceAfter: "2s",
	}
	registration := api.AgentServiceRegistration{
		ID:      global.ServiceId,
		Name:    global.AppConf.ConsulConfig.ServiceName,
		Tags:    global.AppConf.ConsulConfig.Tags,
		Port:    int(global.AppConf.Port),
		Address: global.AppConf.Ip,
		Check:   check,
	}
	err = client.Agent().ServiceRegister(&registration)
	if err != nil {
		zap.S().Error(err)
		return
	}
}
